package com.morehair.service.admin.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.morehair.bean.bo.admin.*;
import com.morehair.bean.pojo.*;
import com.morehair.bean.vo.admin.*;
import com.morehair.mapper.*;
import com.morehair.service.admin.SystemService;
import com.morehair.utils.Md5Util;
import com.morehair.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Author  kkw
 * Date  2021/6/4 21:15
 * Version 1.0
 * Description :
 */
@Service
@Transactional
public class SystemServiceImpl implements SystemService {

    @Autowired
    SystemMapper systemMapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    LogMapper logMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    StorageMapper storageMapper;



    @Override
    public DashboardVo countAll() {
        DashboardVo dashboardVo = new DashboardVo();
        dashboardVo.setGoodsTotal(systemMapper.selectAllGoodsNum());
        dashboardVo.setUserTotal(systemMapper.selectAllUserNum());
        dashboardVo.setProductTotal(systemMapper.selectAllProductNum());
        dashboardVo.setOrderTotal(systemMapper.selectAllOrderNum());
        return dashboardVo;
    }

    @Override
    public TotalAndItemsVo<Admin> selecetAdminsByBo(AdminBo adminBo) {
        PageHelper.startPage(adminBo.getPage(),adminBo.getLimit());
        AdminExample adminExample = new AdminExample();
        adminExample.setOrderByClause(adminBo.getSort()+" "+adminBo.getOrder());
        AdminExample.Criteria criteria = adminExample.createCriteria();
        String username = adminBo.getUsername();
        criteria.andDeletedEqualTo(false);
        if (!StringUtil.isEmpty(username)) {
            criteria.andUsernameLike("%"+ username +"%");
        }
        List<Admin> admins = adminMapper.selectByExample(adminExample);

        //获取分页信息
        PageInfo<Admin> adminPageInfo = new PageInfo<>(admins);
        long total = adminPageInfo.getTotal();
        TotalAndItemsVo<Admin> adminTotalAndItemsVo = new TotalAndItemsVo<>();
        adminTotalAndItemsVo.setItems(admins);
        adminTotalAndItemsVo.setTotal(total);
        return adminTotalAndItemsVo;
    }

    @Override
    public List<OptionVo> selectAllRole() {
        List<OptionVo> optionVos=systemMapper.selectAllRole();
        return optionVos;
    }

    @Override
    public Admin creatAdmin(Admin admin) throws NoSuchAlgorithmException {
        int i=systemMapper.selectAdminByUsername(admin.getUsername());
        if (i != 0) {
            return null;
        }
        String password = Md5Util.getMd5(admin.getPassword());
        admin.setPassword(password);
        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        adminMapper.insertSelective(admin);
        return admin;
    }

    @Override
    public Admin updateAdmin(Admin admin) throws NoSuchAlgorithmException {
//        Integer id=systemMapper.selectAdminIdByUsername(admin.getUsername());
        int count=systemMapper.selectAdminNumByUsername(admin.getUsername());
        if (count>1) {
            return null;
        }
        String password = Md5Util.getMd5(admin.getPassword());
        admin.setPassword(password);
        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        adminMapper.updateByPrimaryKeySelective(admin);
        return admin;
    }

    @Override
    public boolean deleteAdmin(Admin admin) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        if (username.equals(admin.getUsername())){
            return false;
        }
        admin.setDeleted(true);
        adminMapper.updateByPrimaryKeySelective(admin);
        return true;
    }

    @Override
    public TotalAndItemsVo<Role> selectAllRoleBypage(RoleBo roleBo) {
        PageHelper.startPage(roleBo.getPage(), roleBo.getLimit());
        RoleExample roleExample = new RoleExample();
        roleExample.setOrderByClause(roleBo.getSort()+" "+ roleBo.getOrder());
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        String name = roleBo.getName();
        if (!StringUtil.isEmpty(name)){
            criteria.andNameLike("%"+name+"%");
        }
        List<Role> roles = roleMapper.selectByExample(roleExample);

        PageInfo<Role> rolePageInfo = new PageInfo<>(roles);
        long total = rolePageInfo.getTotal();
        return new TotalAndItemsVo<Role>(total,roles);
    }

    @Override
    public Role insertRole(Map<String, String> map) {
        String name = map.get("name");
        int i=systemMapper.selectRoleByName(name);
        if (i != 0) {
            return null;
        }
        Role role = new Role();
        role.setName(name);
        role.setDesc(map.get("desc"));
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        roleMapper.insertSelective(role);
        return role;
    }

    @Override
    public Role updateRole(Role role) {
        int id=systemMapper.selectRoleIdByName(role.getName());
        if (id != role.getId()) {
            return null;
        }
        role.setUpdateTime(new Date());
        roleMapper.updateByPrimaryKeySelective(role);
        return role;
    }

    @Override
    public boolean deleteRole(Role role) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> roleIdList=systemMapper.selectAdminRoleId();
        for (String s : roleIdList) {
            Integer[] integers = objectMapper.readValue(s, Integer[].class);
            for (Integer integer : integers) {
                if (integer == role.getId()) {
                    return false;
                }
            }
        }
        role.setDeleted(true);
        roleMapper.updateByPrimaryKeySelective(role);
        return true;
    }

    @Override
    public TotalAndItemsVo<Log> selectLogsByPage(LogBo logBo) {
        PageHelper.startPage(logBo.getPage(),logBo.getLimit());
        LogExample logExample = new LogExample();
        logExample.setOrderByClause(logBo.getSort()+" "+logBo.getOrder());
        LogExample.Criteria criteria = logExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (!StringUtil.isEmpty(logBo.getName())) {
            criteria.andAdminLike("%"+logBo.getName()+"%");
        }

        List<Log> logs = logMapper.selectByExample(logExample);

        PageInfo<Log> logPageInfo = new PageInfo<>(logs);
        long total = logPageInfo.getTotal();
        return new TotalAndItemsVo<Log>(total,logs);
    }

    @Override
    public PermissionVo getPermission(Integer roleId) {
        PermissionVo permissionVo = new PermissionVo();
        List<ClassVo> firstList=new ArrayList<>();
        List<AllPermissionPojo> permissionPojoList=systemMapper.selectAllPermissionByType(1);
        for (AllPermissionPojo allPermissionPojo : permissionPojoList) {
            Integer code = allPermissionPojo.getCode();
            ArrayList<ClassVo> children2List = new ArrayList<>();
            int min=code*100;
            int max=(code+1)*100;

            List<AllPermissionPojo> permissionPojoLisChildren1=systemMapper.selectAllPermissinBetweenCode(min,max);
            for (AllPermissionPojo permissionPojo : permissionPojoLisChildren1) {
                Integer code1 = permissionPojo.getCode();
                List<ClassVo> children3List=new ArrayList<>();
                int min1=code1*100;
                int max1=(code1+1)*100;

                List<AllPermissionPojo> permissionPojoLisChildren2=systemMapper.selectAllPermissinBetweenCode(min1,max1);
                for (AllPermissionPojo pojo : permissionPojoLisChildren2) {
                    ClassVo classVo3 = new ClassVo();
                    classVo3.setId(pojo.getName());
                    classVo3.setLabel(pojo.getLabel());
                    classVo3.setApi(pojo.getApi());
                    children3List.add(classVo3);
                }
                ClassVo classVo2 = new ClassVo();
                classVo2.setId(permissionPojo.getName());
                classVo2.setLabel(permissionPojo.getLabel());
                classVo2.setChildren(children3List);
                children2List.add(classVo2);
            }
            ClassVo classVo1 = new ClassVo();
            classVo1.setId(allPermissionPojo.getName());
            classVo1.setLabel(allPermissionPojo.getLabel());
            classVo1.setChildren(children2List);

            firstList.add(classVo1);
        }
        permissionVo.setSystemPermissions(firstList);

        List<String> permissions=systemMapper.selectPermissionByRoleId(roleId);
        permissionVo.setAssignedPermissions(permissions);

        return permissionVo;
    }

    @Override
    public boolean changePermission(RolePermissionBo rolePermissionBo) {
        Integer id = rolePermissionBo.getRoleId();
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andUsernameEqualTo(username).andDeletedEqualTo(false);
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        Integer[] roleIds = admins.get(0).getRoleIds();
        for (Integer roleId : roleIds) {
            if (roleId == id) {
                return false;
            }
        }
        int i=systemMapper.deletePermissionByRoleId(id);
        List<String> permissions = rolePermissionBo.getPermissions();
        Permission permission1 = new Permission();
        permission1.setRoleId(id);
        permission1.setUpdateTime(new Date());
        for (String permission : permissions) {
            permission1.setPermission(permission);
            permissionMapper.insertSelective(permission1);
        }
        return true;
    }

    @Override
    public TotalAndItemsVo<Storage> getStorage(StorageListBo storageListBo) {
        PageHelper.startPage(storageListBo.getPage(),storageListBo.getLimit());
        StorageExample storageExample = new StorageExample();
        storageExample.setOrderByClause(storageListBo.getSort()+" "+storageListBo.getOrder());
        StorageExample.Criteria criteria = storageExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        String name = storageListBo.getName();
        String key = storageListBo.getKey();
        if (!StringUtil.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        } else if (!StringUtil.isEmpty(key)) {
            criteria.andKeyLike("%" + key + "%");
        }
        List<Storage> storages = storageMapper.selectByExample(storageExample);
        PageInfo<Storage> storagePageInfo = new PageInfo<>(storages);
        long total = storagePageInfo.getTotal();

        return new TotalAndItemsVo<>(total,storages);
    }
}
